package token

import (
	"crypto/rsa"
	"fmt"
	"github.com/golang-jwt/jwt/v4"
)

type JwtTokenVerifier struct {
	PublicKey *rsa.PublicKey
}

func (v *JwtTokenVerifier) Verify(token string) (string, error) {

	t, err := jwt.ParseWithClaims(token, &jwt.RegisteredClaims{}, func(token *jwt.Token) (interface{}, error) {
		return v.PublicKey, nil
	})
	if err != nil {
		return "", fmt.Errorf("can not parse token: %v", err)
	}

	if !t.Valid {
		return "", fmt.Errorf("token not valid: %v", err)
	}

	claims, ok := t.Claims.(*jwt.RegisteredClaims)

	if !ok {
		return "", fmt.Errorf("token clai is not RegisteredClaims: %v", err)
	}

	if err := claims.Valid(); err != nil {
		return "", fmt.Errorf("claim not valid: %v", err)
	}

	return claims.Subject, nil

}
